package cn.rubintry.bug.common.base

import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.viewbinding.ViewBinding
import cn.rubintry.bug.common.base.event.NetWorkFailedEvent
import com.blankj.utilcode.util.ToastUtils
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

abstract class BaseFragment<T : ViewBinding> : Fragment() {

    protected var binding : T ?= null


    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        val mView = inflater.inflate(layoutId() , container , false)
        val bindingClazz = bindingClazz()
        try {
            val bindMethod = bindingClazz.getDeclaredMethod("bind", View::class.java)
            bindMethod.isAccessible = true
            binding = bindMethod.invoke(this , mView) as? T
        }catch (e : Exception){
            println(e)
        }
        initView()
        observeData()
        return binding?.root
    }

    abstract fun layoutId() : Int

    abstract fun initView()


    abstract fun observeData()

    abstract fun bindingClazz() : Class<out ViewBinding>

    protected abstract fun onNetWorkError(msg: String);

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun netWorkError(event: NetWorkFailedEvent){
        ToastUtils.showShort(event.msg)
        onNetWorkError(event.msg)
    }



}